import axios from 'axios';

// 创建axios实例
const http = axios.create({
  baseURL: process.env.BASE_API || '/api/', // api的base_url
  timeout: 50000, // 请求超时时间
});

const errHandler = (err) => {
  if (err.name === 'SyntaxError') {
    return;
  }
  const response = err.response || {};
  const {
    code: errCode,
    message: errMsg
  } = response;
  let msg = '服务器未知异常';
  if (errMsg && String(errCode) !== '404') {
    msg = errMsg;
  }
  // Toast.fail(msg);
  console.log(msg);
};

// request拦截器
http.interceptors.request.use((config) => {
  const token = localStorage.getItem('LINZ_BLOG_TOKEN');
  if (token) {
    // Bearer是JWT的认证头部信息
    config.headers.common['Authorization'] = 'Bearer ' + token;
  }
  return config;
}, (error) => {
  return Promise.reject(error);
});

// respone拦截器
http.interceptors.response.use(
  response => {
    // 没登录 就移除本地的token
    if (response.data && response.data.code === 403) {
      localStorage.removeItem('LINZ_BLOG_TOKEN');
    }
    return response.data;
  },
  (error) => {
    console.log(`err ${error}`); // for debug
    errHandler(error);
    return Promise.reject(error);
  },
);

export default http;